<template>
  <div class="role_add">
    <el-dialog :visible.sync="visible" @close="closeHanler" width="957px"
             :title="!dataForm.id ? $t('add') : formCode?formCode:$t('update')"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="name"
                    :label="$t('role.name')" style="margin-bottom: 23px;">
        <el-input v-model="dataForm.name"
                  :placeholder="$t('role.name')" :readonly="formCode?true:false"></el-input>
      </el-form-item>
      <el-form-item prop="remark"
                    :label="$t('role.remark')" style="margin-bottom: 23px;">
        <el-input v-model="dataForm.remark"
                  :placeholder="$t('role.remark')" :readonly="formCode?true:false"></el-input>
      </el-form-item>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="Menu Scope" name="menuscope">
          <div v-loading="loading">
            <el-checkbox @change="isShowAllChange" v-model="isShowAll">Show all permission</el-checkbox>
            <el-tree :data="menuList" 
                      :props="{ label: 'name', children: 'children' }"
                      node-key="id"
                      ref="menuListTree"
                      accordion
                      show-checkbox>
            </el-tree>
          </div>
        </el-tab-pane>
        <el-tab-pane label="Assets Scope" name="assetsscope" >
          <AssetsScope v-if="visible" ref="AssetsScope" :FatheractiveName="activeName" :loading2.sync="loading2" :isDisabled.sync="isDisabled" :roleId="dataForm.id"></AssetsScope>
        </el-tab-pane>
      </el-tabs>
      <!-- <el-row  v-show="false"> -->
        <!-- <el-col :span="12">
          <el-form-item size="mini"
                        :label="$t('role.menuList')">
            <el-card shadow="never"
                     class="aui-card--fill">
              <el-checkbox @change="isShowAllChange" v-model="isShowAll">Show all permission</el-checkbox>
              <el-tree :data="menuList"
                       :props="{ label: 'name', children: 'children' }"
                       node-key="id"
                       ref="menuListTree"
                       v-loading="treeLoading"
                       accordion
                       :check-strictly="true"
                       show-checkbox>
              </el-tree>
            </el-card>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item size="mini"
                        :label="$t('role.deptList')">
            <el-card shadow="never"
                     class="aui-card--fill">
              <el-tree :data="deptList"
                       :props="{ label: 'name', children: 'children' }"
                       node-key="id"
                       ref="deptListTree"
                       accordion
                       :check-strictly="true"
                       show-checkbox>
              </el-tree>
            </el-card>
          </el-form-item>
        </el-col> -->
      <!-- </el-row> -->
    </el-form>
    <template slot="footer">
      <el-button size="small" :disabled="loading||loading2 ||isDisabled"
                 @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button size="small" :disabled="loading||loading2 ||isDisabled"
                 type="primary"
                  v-if="!formCode"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import AssetsScope from '@/views/modules/tenant/assets-scope.vue'
export default {
  components: {
    AssetsScope
  },
  data () {
    return {
      isShowAll: false,
      visible: false,
      treeLoading: false,
      menuList: [],
      deptList: [],
      dataForm: {
        id: '',
        name: '',
        menuIdList: [],
        deptIdList: [],
        remark: ''
      },
      formCode: '',
      activeName: 'menuscope',
      loading: false,
      loading2: false,
      isDisabled: false
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeHanler () {
      this.permissionList = []
      // if(this.$refs.AssetsScope){
      //   this.$refs.AssetsScope.reset()
      // }
      Object.assign(this.$data, this.$options.data()) 
    },
    handleClick(val) {
      this.$refs.AssetsScope.handleClick()
    },
    isShowAllChange () {
      this.getMenuList()
    },
    init () {
      this.loading = true
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([])
        // this.$refs.deptListTree.setCheckedKeys([])
        Promise.all([
          this.getMenuList(),
          this.getDeptList()
        ]).then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
        }).finally(() => {
          this.loading = false
        })
      })
    },
    getMenuList () {
      this.treeLoading = true
      return this.$interface.system.getMenuSelectApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.menuList = res.data
          if (!this.isShowAll) {
            this.menuList.forEach(item => {
              if (item.url === 'mspbots/reports/index' || item.url === 'mspbots/widget/index' || item.url === 'mspbots/dataset/index') {
                item.children = item.children.filter(it => {
                  return !(it.name.startsWith('dashboard-')) && !(it.name.startsWith('widget-')) && !(it.name.startsWith('dataset-'))
                })
              }
            })
          }
          if (this.formCode) this.treeNodesDisabled(this.menuList)
          this.treeLoading = false
        }).catch(() => { })
    },
    getDeptList () {
      return this.$interface.system.getDeptListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (this.formCode) this.treeNodesDisabled(res.data)
          this.deptList = res.data
        }).catch(() => { })
    },
    treeNodesDisabled (data) {
      for (let i = 0; i < data.length; i++) {
        let list = data[i]
        list.disabled = true
        if (list.children.length > 0) this.treeNodesDisabled(list.children)
      }
    },
    getInfo () {
      this.$interface.system.getRoleInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          this.dataForm.menuIdList.forEach(item => this.$refs.menuListTree.setChecked(item, true))
          // this.$refs.deptListTree.setCheckedKeys(this.dataForm.deptIdList)
        }).catch(() => { })
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.dataForm.menuIdList = [
          ...this.$refs.menuListTree.getHalfCheckedKeys(),
          ...this.$refs.menuListTree.getCheckedKeys()
        ]
        // this.dataForm.deptIdList = this.$refs.deptListTree.getCheckedKeys()
        if(this.$refs.AssetsScope){
          this.dataForm = {
            ...this.dataForm,
            assetsSave:this.$refs.AssetsScope.getValue()
          }
          delete this.dataForm.assets
        }
        this.loading = true
        this.loading2 = true
        const changeRole = () => {
          if (!this.dataForm.id) {
            return this.$interface.system.postRole(this.dataForm)
          } else {
            return this.$interface.system.putRole(this.dataForm)
          }
        }
        changeRole().then(({ data: res }) => {
          this.$nextTick(()=>{
            this.loading = false
            this.loading2 = false
          })
          if (res.code !== 0) {
            if(res.code === 10052) {
              return this.$showErrorWithAssetList(res)
            }
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { 
          this.loading = false
          this.loading2 = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss" scoped>
.role_add {
  .el-form {
    .el-form-item {
      margin-bottom: 22px!important;
    }
  }
}
</style>
